package com.comut.crud.bo;

import com.comut.crud.dao.ReportDao;
import com.comut.crud.ejb.interfaces.IReportAction;
import com.comut.crud.pojo.mobile.ReportInfo;

import java.io.StringReader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;

import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;


/**
 * Issue: IFL-1571
 *
 * @author celia calcada
 */
public class ReportHandler implements IReportAction {

    private static final Logger _logger = Logger.getLogger(ReportHandler.class.getName());
    private Connection _connection;
    private ReportDao _reportDao;

    /**
     *
     * @param connection
     */
    public ReportHandler(Connection connection) {
        this._connection = connection;
        this._reportDao = new ReportDao(_connection);
    }


    /**
     *  
     */
    public ReportInfo[] getReportsUserId(int userId, String language) {
        ResultSet resultSet = _reportDao.getReportsUserId(userId, language);

        ArrayList<ReportInfo> list = new ArrayList<ReportInfo>();

        try {
            while (resultSet.next()) {
                ReportInfo reportInfo = new ReportInfo();

                String xmlParameters = resultSet.getString("parameters");
                

                reportInfo.setId(resultSet.getInt("id"));
                reportInfo.setName(resultSet.getString("name"));
                reportInfo.setLanguage(language);
                setGroupsAndDefaultGroupIndex(xmlParameters,reportInfo);
                list.add(reportInfo);
            }
        } catch (Exception ex) {
            _logger.log(Level.SEVERE, null, ex);
        }

        ReportInfo[] ret = new ReportInfo[list.size()];
        return list.toArray(ret);
    }
    
    private void setGroupsAndDefaultGroupIndex(String xmlParameters,ReportInfo reportInfo) {
        ArrayList<String> groups = new ArrayList<String>();
        int defaultIndex=-1;
        
        try {
            if (xmlParameters != null && xmlParameters.length() > 0) {
                DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
                builderFactory.setNamespaceAware(true);
                DocumentBuilder builder = builderFactory.newDocumentBuilder();
                Document document = builder.parse(new InputSource(new StringReader(xmlParameters)));
                XPath xpath = XPathFactory.newInstance().newXPath();
                NodeList nodes = (NodeList) xpath.evaluate("/parameters/groups/group", document.getDocumentElement(), XPathConstants.NODESET);
                
                for (int nodeIndex = 0; nodeIndex < nodes.getLength(); nodeIndex++) {
                    Element element = (Element) nodes.item(nodeIndex);
                    String group = element.getTextContent();
                    String defaultValue = element.getAttribute("default");
                    
                    if(defaultValue!=null && defaultValue.compareTo("true")==0){
                        defaultIndex = nodeIndex;
                    }
                    
                    groups.add(group);                    
                }
            }
        } catch (Exception ex) {
        }
        
        String[] ret = new String[ groups.size() ];
        reportInfo.setGroups(   groups.toArray(ret) ); 
        reportInfo.setDefaultGroupIndex(defaultIndex);
    }
}
